"""改造产品过期功能"""

from datetime import timedelta

from odoo import models, api, fields
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError


class Lot(models.Model):
    _inherit = 'stock.production.lot'

    nd_production_date = fields.Datetime('生产日期')


class Quant(models.Model):
    _inherit = 'stock.quant'

    expire_date = fields.Datetime('有效期至', related="lot_id.life_date", store=True)
    expire_date_new = fields.Datetime('有效期至', related="lot_id.life_date", store=True)
    nd_production_date = fields.Datetime('生产日期', related="lot_id.nd_production_date", store=True)


class SOLineLot(models.Model):
    _inherit = 'nd.sale.line.lot'

    nd_production_date = fields.Datetime('生产日期', related="lot_id.nd_production_date", store=True)
    expire_date = fields.Datetime('过期日期', related="lot_id.life_date", store=True)


class GSPCheck(models.AbstractModel):
    _inherit = 'gsp.business.check'

    def apply_gsp_manage(self):
        """在原来的基础添加对于有效期的检查(只限销售单sale.order)"""
        for order in self:
            now = fields.Datetime.now()
            if order._name == 'sale.order':
                lot_lines = order.mapped('order_line.nd_lot_lines')
                for line in lot_lines:
                    if line.expire_date and line.expire_date < now:
                        raise UserError(f'批次{line.lot_id.name}已经过期"{line.expire_date}"!')
        return super().apply_gsp_manage()



